////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax.IOnDialogButtonClick;
import cc.telecomdigital.tdstock.ExceptionHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.Activity_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.ProgressView;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Services.LS_Authentication.LS_Authentication_Result;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;
import cc.telecomdigital.tdstock.activity.groups.index.IndexActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.PortfolioActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;

/**
 * login screen entry
 * 
 * @author haibo
 */
public class VerifyActiveCodeActivity extends Activity_Framework implements OnClickListener
{
	private static String			TAG							= VerifyActiveCodeActivity.class.getSimpleName();
	protected static String			_menu_exit_app_res			= null;
	protected static String			_menu_gen_launcher_res		= null;

	protected static final String	ACTION_INSTALL_SHORTCUT		= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String	EXTRA_SHORTCUT_DUPLICATE	= "duplicate";

	public static final int			EXIT_APP					= Menu.FIRST;
	public static final int			CREATE_LAUNCHER				= Menu.FIRST + 1;
//	private static String			SUCCESS_CODE				= "0";
	
	public static String			activeCode;
	private SharedPreferences		_prefs						= null;
	private Button					_return;
	private Button					_confirm;
	private EditText				_activationCode;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		ExceptionHandler.register(this);
		setContentView(R.layout.verifyactivecode);
		
		_prefs = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(R.string.app_launcher);
		
		_activationCode = (EditText) findViewById(R.id.trial_realtime_active_code);
		
		_return = (Button) findViewById(R.id.btn_returnpre);
		_confirm = (Button) findViewById(R.id.btn_confirm);
		_return.setOnClickListener(this);
		_confirm.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v)
	{
		if (v == _return)
		{
			Intent intent = new Intent(this, RealtimeStockActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			SwitchFreeActivity(RealtimeStockActivity.class, intent);
			TDStockLog.i(TAG, "auth --> return");
		}
		else if (v == _confirm)
		{
			if (!isValidActivationCode())
			{
				new CustomizeDialog(VerifyActiveCodeActivity.this, getResources().getString(R.string.info),
						getResources().getString(R.string.please_entry_true_verify_code), getResources().getString(R.string.ok))
				{
					@Override
					public void onClick(View v)
					{
						if (v == okButton)
						{
							dismiss();
							_activationCode.requestFocus();
						}
					}
				}.show();
				return;
			}
			
			// ------------------commit by haibo for no use code & only  allow to get devicdId by using SystemInfo or  DeviceInfo  or  ProviderOperationHelper ------------------
//			String prefDeviceId = _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
//			TDStockLog.i(TAG, "prefDeviceId = " + prefDeviceId);
			// ------------------commit by haibo for no use code & only  allow to get devicdId by using SystemInfo or  DeviceInfo  or  ProviderOperationHelper ------------------
			
			TrialLogonToApp(_activationCode.getText().toString());
			
//			if (prefDeviceId.trim().length() < 2)
//			{
//				TDStockLog.i(TAG, "auth --> asynctask");
//				new LogonAsyncTask().execute(_activationCode.getText().toString());
//			}
//			else
//			{
//				TDStockLog.i(TAG, "auth --> excetucode");
//				autoLoginExcetuCode(prefDeviceId);
//			}
		}

		_activationCode.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
//				final int[] doneKeyCode = { KeyEvent.KEYCODE_ENTER };
				if (event.isTracking() && !event.isCanceled())
				{
					return false; // this code copied from Activity.class
				}

				if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_TAB)
				{
					try
					{
						Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						InputMethodManager imm = (InputMethodManager) service;
						imm.hideSoftInputFromWindow(_activationCode.getWindowToken(), 0);
						_confirm.performClick();
						Thread.yield();
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				return false;
			}
		});
	}

	/**
	 * 执行自动登录代码
	 */
//	private void autoLoginExcetuCode(String deviceId)
//	{
//		if (activeCode != null && activeCode.length() >= 1)
//		{
//			findViewById(R.id.verifyactivecode_background).setVisibility(View.GONE);
//			findViewById(R.id.splash_background).setVisibility(View.VISIBLE);
//		}
//		// Zor 2011-12-14
//		// String deviceId = SystemInfo.getDeviceId(VerifyActiveCodeActivity.this);
//		// String edevinfo = SystemInfo.getDeviceExtraInfo(VerifyActiveCodeActivity.this);
//		try
//		{
//			ActivationCodeAuth auth = new ActivationCodeAuth(deviceId, _activationCode.getText().toString());
//			String[] auth_info = auth.getAuthentication();
//			Logon(auth_info);
//		}
//		catch (Exception e)
//		{
//			e.printStackTrace();
//			TDStockLog.i(TAG, "auth --> exception = " + e.toString());
//		}
//	}
//	
//	private class LogonAsyncTask extends AsyncTask<String, Void, Void>
//	{
//		String[]		auth_info;
//		ProgressDialog	_dialog;
//		// String deviceId;
//		String[]		deviceId_auth;
//
//		@Override
//		protected Void doInBackground(String... params)
//		{
//			try
//			{
//				deviceId_auth = SystemInfo.GetDeviceIdAuthWifiMac(VerifyActiveCodeActivity.this);
//				if (SystemInfo.SUCCESS_CODE.equals(deviceId_auth[0]))
//				{
//					// Zor 2011-12-14
//					// String edevinfo = SystemInfo.getDeviceExtraInfo(VerifyActiveCodeActivity.this);
//					ActivationCodeAuth auth = new ActivationCodeAuth(deviceId_auth[1], params[0]);
//					auth_info = auth.getAuthentication();
//				}
//			}
//			catch (Exception e)
//			{
//				e.printStackTrace();
//				TDStockLog.i(TAG, "auth --> exception = " + e.toString());
//			}
//			return null;
//		}
//
//		@Override
//		protected void onCancelled()
//		{
//			super.onCancelled();
//			if (_dialog != null)
//				_dialog.dismiss();
//		}
//
//		@Override
//		protected void onPreExecute()
//		{
//			super.onPreExecute();
//			_dialog = new ProgressDialog(VerifyActiveCodeActivity.this, Html.fromHtml("正在初始化數據並連接至伺服器<br/>請稍候...").toString());
//			_dialog.show();
//		}
//
//		@Override
//		protected void onPostExecute(Void result)
//		{
//			super.onPostExecute(result);
//			if (_dialog != null)
//				_dialog.dismiss();
//
//			if (SystemInfo.SUCCESS_CODE.equals(deviceId_auth[0]))
//			{
//				Logon(auth_info);
//			}
//			else
//			{
//				if (deviceId_auth[2].length() < 2)
//					deviceId_auth[2] = "操作失敗，請稍後再试。";
//
//				new CustomizeDialog(VerifyActiveCodeActivity.this, getResources().getString(R.string.info),
//						deviceId_auth[2], getResources().getString(R.string.ok))
//				{
//					@Override
//					public void onClick(View v)
//					{
//						if (v == okButton)
//						{
//							// SystemInfo.initLoginApp(getApplicationContext(), CommonDefn.ModeType.DELARY, null, null, null, null);
//							// forwardToMainActivity();
//							dismissAll();
//							((ITDLApplication) getApplicationContext()).setExitApp(true);
//							exitApp();
//						}
//					}
//				}.show();
//			}
//		}
//	}
//
//	private void Logon(String[] auth_info/* , String deviceId */)
//	{
//		try
//		{
//			TDStockLog.i(TAG, "auth --> " + auth_info[0]);
//			String message = "";
//			if (auth_info[3].equals(SUCCESS_CODE) && auth_info[1].trim().length() >= 1)
//			{
//				boolean isAutoLogin = _prefs.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, true);
//				boolean isSendCode = _prefs.getBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, true);
//				_prefs.edit().putBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, isAutoLogin).commit();
//				_prefs.edit().putBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, isSendCode)
//							.putString(CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, _activationCode.getText().toString()).commit();
//				// 如果未存储 deviceid 则将其保存起来
//				/*
//				 * String pdeviceId =
//				 * _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
//				 * if(pdeviceId.length() <= 1) {
//				 * _prefs.edit().putString(CommonDefn.PREFERENCE_DEVICE_ID,
//				 * deviceId).commit(); }
//				 */
//				BaseActivity.errorMsg = auth_info[2];
//				SystemInfo.initLoginApp(getApplicationContext(), CommonDefn.ModeType.ACTIVECODE, null, null, auth_info[0], auth_info[1]);
//
//				((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER, ITDLApplication.DEFAULT_INT_VALUE);
//				((ITDLApplication) getApplicationContext()).setReadyToChangeMode(true);
//
//				// ((ITDLApplication)
//				// getApplicationContext()).getLightStreamerClientForNew();
//
//				String svcPlan = auth_info[4]; // svcPlan i.e.
//												// 1111111110Z110000001
//				TDStockLog.d(TAG, "svcPlan=" + svcPlan);
//				((ITDLApplication) getApplicationContext()).SetServicePlan(svcPlan);
//
//				forwardToMainActivity();
//				return;
//			}
//			else if (auth_info[2].trim().length() >= 1)
//			{
//				message = auth_info[2];
//			}
//			else
//			{
//				message = getResources().getString(R.string.donot_validate_verify_code);
//			}
//			findViewById(R.id.verifyactivecode_background).setVisibility(View.VISIBLE);
//			findViewById(R.id.splash_background).setVisibility(View.GONE);
//			new CustomizeDialog(VerifyActiveCodeActivity.this, getResources().getString(R.string.info), message, getResources().getString(R.string.ok)).show();
//		}
//		catch (Exception e)
//		{
//			e.printStackTrace();
//			TDStockLog.i(TAG, "auth --> exception =" + e.toString());
//		}
//	}

	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(this)
			.setTitle(getResources().getString(R.string.info))
			.setMessage(getResources().getString(R.string.application_exit_tips))
			.setIcon(getResources().getDrawable(R.drawable.help_menu_icon))
			.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialoginterface, int i)
				{
					((ITDLApplication) getApplicationContext()).setExitApp(true);
					exitApp();
				}
			}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int whichButton)
				{
				}
			}).show();
	}

	public void exitApp()
	{
		finish();
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}

	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(this.getPackageName(), ".activity.SplashActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext()).setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
		else
		{
			if (activeCode != null && activeCode.length() >= 1)
			{
				_activationCode.setText(activeCode);
				_confirm.performClick();
			}
		}
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();

		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
	}

	private boolean isValidActivationCode()
	{
		boolean result = _activationCode.getText().toString().length() >= 1; // simply check
		return result;
	}

	private void forwardToMainActivity()
	{
		// Change ModeType Update UI.
		CurrentStockInfoActivity.isChangeModeType = true;
		PortfolioActivity.isChangeModeType = true;
		IndexActivity.isChangeModeType = true;

		appHost.LSClient_Disconnect();
		Intent intent = new Intent(this, RealtimeStockActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		SwitchForwardActivity(RealtimeStockActivity.class, intent);
	}

	protected void ShowMessageDialog(String msgContent)
	{
		CustomizeDialog promptBox;
		promptBox = new CustomizeDialog(this, "提示", msgContent, false)
		{
			@Override
			public void onClick(View v)
			{
				super.onClick(v);
			}
		};
		promptBox.show();
	}
	
	private void TrialLogonToApp(final String iActivateCode)
	{
		TDStockLog.d(TAG, "TrialLogin=>activateCode: " + iActivateCode);
		final ProgressView progress = new ProgressView(this);
		H_CODE statusCode;
		statusCode = HttpAppInfo.SendFrameworkTrialAuthRequest(iActivateCode, new ILS_UserClient_Authentication_Report()
		{
			@Override
			public void LS_UserClient_Authentication_Response(LS_UserClient_Authentication_Result iResponse)
			{
				progress.DismissProgress();
				TDStockLog.d(TAG, "TrialLogonToApp=>callback: statusCode=" + iResponse.statusCode + ", errMsg=" + iResponse.errorMessage);
				//if ((iResponse == null) || (iResponse.successfulSend == false) )				
				if ((iResponse == null) || (iResponse.successfulSend == false) || (iResponse.statusCode == null))
				{
//					Toast.makeText(actContext, "登錄失敗!", Toast.LENGTH_SHORT).show();
					//At this point we are pretty sure there are non message reply
					ShowMessageDialog(getString(R.string.login_failure));
//					ShowMessageDialog(iResponse==null?getResources().getString(R.string.login_failure):iResponse.errorMessage);
					return;
				}

//				if ((iResponse.statusCode == null) || !iResponse.statusCode.equals("0")) // 處理Wifi消息
//				{
////					Toast.makeText(actContext, "登錄失敗:"+ " statusCode=" + iResponse.statusCode + ", errMsg="+iResponse.errorMessage, Toast.LENGTH_SHORT).show();
//					ShowMessageDialog(iResponse.errorMessage);
//					return;
//				}

				if (iResponse.statusCode.equals("0"))
				{
					if(!iResponse.errorMessage.trim().equals(""))
						BaseActivity.loginResult = new LS_Authentication_Result(iResponse);						
					
					if(_prefs != null)
					{
						boolean isAutoLogin = _prefs.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, true);
						boolean isSendCode = _prefs.getBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, true);
						_prefs.edit().putBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, isAutoLogin).commit();
						_prefs.edit().putBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, isSendCode)
									.putString(CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, iActivateCode).commit();
					}
					((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER, ITDLApplication.DEFAULT_INT_VALUE);
					((ITDLApplication) getApplicationContext()).setReadyToChangeMode(true);
					
					SystemInfo.initLoginApp(getApplicationContext(), CommonDefn.ModeType.ACTIVECODE, null, null, null, null);
					((ITDLApplication) getApplicationContext()).SetServicePlan(appHost.GetLSClient_ServicePlan());
					forwardToMainActivity();
					return;
				}
				
				//For Non 0 status Code
				final String            extraContent;
				CustomizeDialogDualMax  msgDialog;
				
				msgDialog = new CustomizeDialogDualMax(actContext);
				msgDialog.SetOnCancelFeature(false, null);
				
				msgDialog.SetHeader("提示");
				msgDialog.SetMsgContent(iResponse.errorMessage);
				
				//Create a downloadable message if needed
				extraContent = iResponse.linkContent;
				if ((extraContent != null) && (extraContent.length() != 0 ))
				{
					msgDialog.SetDualButton( iResponse.linkCaption, 
										 new IOnDialogButtonClick()
										{
											@Override
											public void OnResponse()
											{
												Uri    uriObj;
												Intent intentObj;
												String linkContent;
								
												linkContent = extraContent;					
												if ((linkContent == null) || (linkContent.length() == 0))
													return;
												
												intentObj = new Intent(Intent.ACTION_VIEW);
												uriObj = Uri.parse(linkContent);
												intentObj.setData(uriObj);
												startActivity(intentObj);
				}
										}, getString(R.string.ok), null);
				}					
				else
					msgDialog.SetSingleButton(getString(R.string.ok), null);									
				msgDialog.show();					
			}
		});
		
		TDStockLog.d(TAG, "TrialLogin=>status:" + statusCode);
		if(statusCode != H_CODE.OK)
		{
			ShowMessageDialog(getString(R.string.login_failure));
		}
		else
		{
			progress.SetShowDialog(true);
			progress.ShowProgress();
		}
	}
}
